import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, Breadcrumb, theme } from 'antd';
import { useNavigate } from 'react-router-dom';
import CreateSurvey from './CreateSurvey';
import ViewCreatedSurveys from './ViewCreatedSurveys';
import ViewAnsweredSurveys from './ViewAnsweredSurveys';
// 新添加
import WritedSurveys from './WriteSurvey';

const { Header, Content, Footer } = Layout;

const Home = () => {
  const navigate = useNavigate();

  const [selectedKey, setSelectedKey] = useState('create'); // 向组件添加状态变量，控制内容区的输出

  // 新增状态变量，保存问卷标题、描述、题目，提升状态以保留未完成内容
  const [surveyTitle, setSurveyTitle] = useState('');
  const [surveyDescription, setSurveyDescription] = useState('');
  const [questions, setQuestions] = useState([]);

  // 控制是否恢复填写中问卷
  const [continueSurvey, setContinueSurvey] = useState(false);
  const [recoverSurveyId, setRecoverSurveyId] = useState(null);

  // 提取主题变量（颜色、圆角等）
  const {
    token: { colorBgContainer, borderRadiusLG, colorTextBase },
  } = theme.useToken();

  // 点击导航栏的回调函数
  const handleMenuClick = ({ key }) => {
    // 检查是否是填写问卷，并且存在未完成问卷记录
    if (key === 'createsurvey') {
      const unfinishedSurveyId = localStorage.getItem('unfinishedSurveyId');
      if (unfinishedSurveyId) {
        setContinueSurvey(true);
        setRecoverSurveyId(unfinishedSurveyId);
      } else {
        setContinueSurvey(false);
        setRecoverSurveyId(null);
      }
    }
    setSelectedKey(key);
  };

  // 退出按键的回调函数
  const logout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    navigate('/');
  };

  // 菜单项配置
  const menuItems = [
    { key: 'create', label: '创建问卷' },
    { key: 'view', label: '查看已创建的问卷' },
    { key: 'answered', label: '查看我的填写记录' },
    { key: 'createsurvey', label: '填写问卷' },
  ];

  // 根据导航栏的选择，渲染不同的组件到内容区
  // 这里给CreateSurvey传入提升后的状态和更新函数，实现状态共享
  const renderContent = () => {
    switch (selectedKey) {
      case 'create':
        return (
          <CreateSurvey
            title={surveyTitle}
            setTitle={setSurveyTitle}
            description={surveyDescription}
            setDescription={setSurveyDescription}
            questions={questions}
            setQuestions={setQuestions}
          />
        );
      case 'view':
        return <ViewCreatedSurveys />;
      case 'answered':
        return <ViewAnsweredSurveys />;
      case 'createsurvey':
        return (
          <WritedSurveys
            continueSurvey={continueSurvey}
            recoverSurveyId={recoverSurveyId}
            onFinish={() => {
              // 问卷填写完成后，清除恢复状态
              localStorage.removeItem('unfinishedSurveyId');
              setContinueSurvey(false);
              setRecoverSurveyId(null);
            }}
          />
        );
      default:
        return <h2>欢迎使用问卷系统</h2>;
    }
  };

  return (
    <Layout>
      <Header
        style={{
          display: 'flex',
          alignItems: 'center',
          backgroundColor: colorBgContainer, // 根据主题设置背景色
        }}
      >
        <Menu
          mode="horizontal"
          selectedKeys={[selectedKey]}
          items={menuItems}
          // 点击处理函数
          onClick={handleMenuClick}
          style={{
            flex: 1,
            minWidth: 0,
            backgroundColor: colorBgContainer,
            color: colorTextBase,
          }}
        />

        {/* 恢复默认颜色的退出按钮 */}
        <Button type="default" onClick={logout}>
          退出登录
        </Button>
      </Header>

      <div style={{ padding: '0 48px' }}>
        <Breadcrumb style={{ margin: '16px 0' }}>
          <Breadcrumb.Item>Home</Breadcrumb.Item>
          {/* 可选链语法安全地访问 label */}
          <Breadcrumb.Item>{menuItems.find(item => item.key === selectedKey)?.label}</Breadcrumb.Item>
        </Breadcrumb>

        <Layout
          style={{
            padding: '24px',
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
            minHeight: '450px',
          }}
        >
          {/* 根据状态变量的不同渲染不同的内容到内容区 */}
          <Content style={{ padding: '24px', color: colorTextBase }}>
            {renderContent()}
          </Content>
        </Layout>
      </div>

      <Footer style={{ textAlign: 'center' }}>
        The survey system was created by zkk
      </Footer>
    </Layout>
  );
};

export default Home;
